package com.slipper.system.ai.service;

import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.slipper.system.ai.dao.KnowledgeEmbeddingDao;
import com.slipper.system.ai.dao.KnowledgeFileDao;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import com.slipper.system.ai.dao.KnowledgeDao;
import com.slipper.system.ai.bo.KnowledgeBO;

import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;
import com.slipper.util.Tool;
import com.slipper.util.UUID;

@Service
@ReadTransactional
public class KnowledgeService {
    @Resource
    private KnowledgeDao knowledgeDao;
    @Resource
    private KnowledgeFileDao knowledgeFileDao;
    @Resource
    private KnowledgeEmbeddingDao knowledgeEmbeddingDao;
    
    public KnowledgeBO queryBy(String id) {
        return knowledgeDao.queryBy(id);
    }
    
    public List<KnowledgeBO> queryList(KnowledgeBO bo) {
        return knowledgeDao.queryList(bo);
    }
    
    public PageInfo<KnowledgeBO> queryPage(KnowledgeBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(knowledgeDao.queryList(bo));
    }
    
    @WriteTransactional
    public int save(KnowledgeBO bo) {
        if (Tool.isNotBlank(bo.getId())) {
            bo.setUpdateTime(System.currentTimeMillis());
            return knowledgeDao.update(bo);
        } else {
            bo.setId(UUID.getUUID());
            bo.setUpdateTime(System.currentTimeMillis());
            bo.setCreateTime(System.currentTimeMillis());
            return knowledgeDao.insert(bo);
        }
    }

    @WriteTransactional
    public void saveList(List<KnowledgeBO> list) {
        if (list == null) return;

        list.forEach(item -> {
            if (knowledgeDao.queryBy(item.getId()) != null) {
                item.setUpdateTime(System.currentTimeMillis());
                knowledgeDao.update(item);
            } else {
                item.setUpdateTime(System.currentTimeMillis());
                item.setCreateTime(System.currentTimeMillis());
                knowledgeDao.insert(item);
            }
        });
    }
    
    @WriteTransactional
    public int delete(KnowledgeBO bo) {
        if (Tool.isNotBlank(bo.getId())) {
            this.deleteById(bo.getId());
        }

        if (bo.getIds() != null) {
            for (String id : bo.getIds()) {
                this.deleteById(id);
            }
        }
        return 1;
    }

    @WriteTransactional
    public void deleteById(String id) {
        if (Tool.isBlank(id)) return;

        this.knowledgeEmbeddingDao.deleteByKnowledgeId(id);
        this.knowledgeFileDao.deleteByKnowledgeId(id);
        this.knowledgeDao.deleteById(id);
    }
}
